<template>
  <el-dialog v-model="dialogVisible" title="用户注册" width="450px" :close-on-click-modal="false">
    <el-form :model="registerForm" :rules="rules" ref="registerFormRef" label-width="100px">
      <el-form-item label="手机号" prop="phone">
        <el-input 
          v-model="registerForm.phone" 
          placeholder="请输入手机号"
          :prefix-icon="Phone"
        />
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input 
          v-model="registerForm.username" 
          placeholder="请输入用户名"
          :prefix-icon="User"
        />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input 
          v-model="registerForm.password" 
          type="password" 
          placeholder="请输入密码"
          :prefix-icon="Lock"
          show-password
        />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input 
          v-model="registerForm.confirmPassword" 
          type="password" 
          placeholder="请再次输入密码"
          :prefix-icon="Lock"
          show-password
        />
      </el-form-item>
      <el-form-item label="真实姓名" prop="realName">
        <el-input 
          v-model="registerForm.realName" 
          placeholder="请输入真实姓名"
          :prefix-icon="UserFilled"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleRegister">注册</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { User, Lock, Phone, UserFilled } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: Boolean
})

const emit = defineEmits(['update:modelValue'])

const userStore = useUserStore()
const dialogVisible = ref(props.modelValue)
const loading = ref(false)
const registerFormRef = ref()

const registerForm = ref({
  phone: '',
  username: '',
  password: '',
  confirmPassword: '',
  realName: ''
})

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== registerForm.value.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const validatePhone = (rule, value, callback) => {
  const phoneReg = /^1[3-9]\d{9}$/
  if (!phoneReg.test(value)) {
    callback(new Error('请输入正确的手机号'))
  } else {
    callback()
  }
}

const rules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { validator: validatePhone, trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名长度不能少于3位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ]
}

// 清空表单的方法
const resetForm = () => {
  registerForm.value = {
    phone: '',
    username: '',
    password: '',
    confirmPassword: '',
    realName: ''
  }
  registerFormRef.value?.resetFields()
}

watch(() => props.modelValue, (newVal) => {
  dialogVisible.value = newVal
  // 弹窗关闭时清空表单
  if (!newVal) {
    resetForm()
  }
})

watch(dialogVisible, (newVal) => {
  emit('update:modelValue', newVal)
  // 弹窗关闭时清空表单
  if (!newVal) {
    resetForm()
  }
})

const handleRegister = async () => {
  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        await userStore.registerAction(registerForm.value)
        ElMessage.success('注册成功，请登录')
        dialogVisible.value = false
      } catch (error) {
        ElMessage.error('注册失败: ' + error.message)
      } finally {
        loading.value = false
      }
    }
  })
}

const handleCancel = () => {
  dialogVisible.value = false
}
</script>